<template>
  <div
    id="player"
    :style="{
      height: `${height}px`,
      borderTop: `${borderWidth}px ${borderStyle} ${borderColor}`,
    }"
  >
    <!-- 播放器（不显示） -->
    <audio
      ref="player"
      @ended="onended"
      :loop="mode === 0"
      autoplay
      :src="musicSrc"
    ></audio>

    <!-- 歌曲专辑图片 -->
    <el-image
      :style="{
        height: `${realHeight}px`,
        width: `${realHeight}px`,
      }"
      :src="imgsrc"
      fit="cover"
    >
      <div slot="error" class="image-slot">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image>

    <!-- 右边部分 -->
    <div class="player-right">
      <!-- 歌名、歌手、播放按钮、音量 -->
      <div
        :style="{
          height: `${realHeight * 0.5}px`,
        }"
      >
        <!-- 歌名、歌手 -->
        <div class="songName_Artist">{{ name }} - {{ artist }}</div>
        <!-- 播放按钮、音量 -->
        <div style="width: 200px; display: flex; justify-content: space-around">
          <!-- 音量 -->
          <myProgress
            class="player-volume"
            backgroundColor="#4DAF7C"
            @change="onvolumechangeHandler"
            :percentage="volume"
            width="100px"
          ></myProgress>

          <!-- 上一曲按钮 -->
          <i class="el-icon-d-arrow-left player-btn" @click="onprevClick"></i>

          <!-- 播放按钮 -->
          <i
            v-if="isPlaying"
            class="el-icon-video-pause player-btn"
            @click="togglePlay"
          ></i>
          <i
            v-else
            class="el-icon-video-play player-btn"
            @click="togglePlay"
          ></i>
          
          <!-- 下一曲按钮 -->
          <i class="el-icon-d-arrow-right player-btn" @click="onnextClick"></i>

          <!-- 播放模式按钮 -->
          <i
            v-show="mode === 0"
            class="el-icon-refresh player-btn"
            @click="changeMode"
          ></i>
          <i
            v-show="mode === 1"
            class="el-icon-s-unfold player-btn"
            @click="changeMode"
          ></i>
          <i
            v-show="mode === 2"
            class="el-icon-lock player-btn"
            @click="changeMode"
          ></i>
        </div>
      </div>

      <!-- 进度条 -->
      <div
        style="background: white"
        :style="{ height: `${realHeight * 0.1}px` }"
      >
        <myProgress
          backgroundColor="#4DAF7C"
          width="100%"
          @change="onprogresschangeHandler"
          :percentage="progress"
        ></myProgress>
      </div>

      <!-- 歌词、歌曲时间 -->
      <div :style="{ height: `${realHeight * 0.4}px` }">
        <span class="player-time">{{ currentTime }}</span>
        <span class="player-time">{{ currentLyric }}</span>
        <span class="player-time">{{ totalTime }}</span>
      </div>
    </div>
  </div>
</template> 

<script>
import myProgress from "./myProgress";
export default {
  data() {
    return {
      // 播放器dom
      player: null,
      currentTime: "0:00",
      // 歌词对象
      lyricObj: {},
      currentLyric: "",
    };
  },
  computed: {
    // 总时长（时间戳）
    timestamp() {
      let arr = this.totalTime.split(":");
      return arr[0] * 60 + parseInt(arr[1]);
    },
    // 播放器真实高度
    realHeight() {
      return this.height - this.borderWidth - 4;
    },
  },
  methods: {
    // 点击上一曲按钮
    onprevClick() {
      this.$listeners["onprevClick"] && this.$listeners["onprevClick"]();
    },
    // 点击下一曲按钮
    onnextClick() {
      this.$listeners["onnextClick"] && this.$listeners["onnextClick"]();
    },
    // 点击播放按钮
    togglePlay() {
      // 判断是否从外部v-bind.sync传入
      if (this.$listeners["update:isPlaying"]) {
        this.$listeners["update:isPlaying"](!this.isPlaying);
      } else {
        this.isPlaying = !this.isPlaying;
      }

      // 触发player组件的事件
      // this.$listeners.ontoggleplay && this.$listeners.ontoggleplay(this.isPlaying);
    },
    // 点击循环播放/顺序播放按钮
    changeMode() {
      if (this.$listeners["update:mode"]) {
        this.$listeners["update:mode"]((this.mode + 1) % 2);
      } else {
        this.mode = (this.mode + 1) % 2;
      }
      // 触发player组件的事件
      // this.$listeners.onchangeMode && this.$listeners.onchangeMode(this.mode);
    },
    // 点击音量
    onvolumechangeHandler(val) {
      // 更新父组件的volume
      this.$listeners["update:volume"](val);
      // 触发player组件的事件
      this.$listeners.onvolumechange && this.$listeners.onvolumechange(val);
    },
    // 点击进度条
    onprogresschangeHandler(val) {
      // 更新音乐播放进度
      this.player.currentTime = (this.timestamp * val) / 100;
      // 更新父级的progress
      // 限制小数位1位，防止element的props验证错误
      this.$listeners["update:progress"] &&
        this.$listeners["update:progress"](Number(val.toFixed(1)));
      // 触发player组件的事件
      this.$listeners.onprogresschange && this.$listeners.onprogresschange(val);
    },
    // 更新歌词
    updateLyric() {
      let obj = {};
      // 构造歌词对象
      this.lyric.split("[").forEach((item) => {
        item = item.split("]");
        item[0] = item[0].split(".")[0].slice(1);
        obj[item[0]] = item[1];
      });
      this.lyricObj = obj;
    },
    // 播放完毕事件
    onended(e) {
      this.$listeners.onended && this.$listeners.onended(e);
    },
  },
  watch: {
    // 播放暂停
    isPlaying(newVal) {
      if (newVal) {
        this.player.play();
      } else {
        this.player.pause();
      }
    },
    // 音量
    volume(newVal) {
      this.player.volume = newVal / 100;
    },
    // 监听当前进度，更新歌词
    currentTime(newVal) {
      if (this.lyricObj[newVal]) this.currentLyric = this.lyricObj[newVal];
    },
  },
  props: {
    // 是否播放
    isPlaying: {
      type: Boolean,
      default: false,
    },
    // 播放模式
    mode: {
      type: Number,
      default: 0,
    },
    // 歌词
    lyric: {
      default: "",
    },
    // 进度条
    progress: {
      type: Number,
      default: 0,
    },
    // 音量
    volume: {
      type: Number,
      default: 100,
    },
    // 歌曲总时间
    totalTime: {
      type: String,
      default: "0:00",
    },
    //   歌手
    artist: {
      type: String,
      default: "^",
    },
    // 歌名
    name: {
      type: String,
      default: "^",
    },
    //   图片地址
    imgsrc: {
      type: String,
      default: require("../assets/01.jpg"),
    },
    // 音乐播放地址
    musicSrc: {
      type: String,
    },
    // 加上边框的总高度
    height: {
      type: Number,
      default: 53,
    },
    // 顶边框长度
    borderWidth: {
      type: Number,
      default: 1,
    },
    // 顶边框样式
    borderStyle: {
      type: String,
      default: "solid",
    },
    // 顶边框颜色
    borderColor: {
      type: String,
      default: "#4DAF7C",
    },
  },
  updated() {
    this.updateLyric();
  },
  mounted() {
    this.player = this.$refs.player;
    // 监听audio的ontimeupdate事件
    this.player.ontimeupdate = () => {
      let second = parseInt(this.player.currentTime);
      this.currentTime = `${parseInt(second / 60)}:${
        second % 60 > 9 ? second % 60 : `0${second % 60}`
      }`;

      // 限制小数位1位，防止element的props验证错误
      let percent = Number(((second / this.timestamp) * 100).toFixed(1));
      // 更新父级的progress
      this.$listeners["update:progress"] &&
        this.$listeners["update:progress"](percent);
      // 触发player组件的事件
      this.$listeners.onprogresschange &&
        this.$listeners.onprogresschange(percent);
    };
  },
  components: {
    myProgress,
  },
};
</script>

<style lang="scss">
#player {
  width: 100%;
  padding: 2px;
  box-sizing: border-box;
  display: flex;
}

.player-right {
  flex: 1;
}
.player-right > div {
  padding: 2px 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}

.player-btn {
  color: #4daf7c;
  font-size: 20px;
  cursor: pointer;
}
// .player-btn:hover {
//   font-weight: bold;
// }

.player-volume {
  margin-top: 4px;
}
.player-time {
  font-size: 12px;
  color: #4daf7c;
  margin-top: 2px;
}

.songName_Artist {
  width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>